#!/bin/bash

scriptName=${0##*/}
echo $scriptName
#判断命令是否在PATH中及是否安装
command1=ansible

if ! type -p $command1 &>/dev/null; then
    echo "$command1命令不在 PATH中"
fi
if ! type -p $command1 &>/dev/null; then
    printf '%s\n' "error: $command1 没有安装,退出..."
    exit 1
fi

#变量"basepath"的路径为本脚本路径
basepath=$(cd `dirname $0`; pwd)
inventory=$(egrep "^inventory " $basepath/ansible.cfg|awk {'print $3'})
inventory=$basepath/$inventory
roles=$(egrep "^roles_path" $basepath/ansible.cfg|awk {'print $3'})
roles=$basepath/$roles
function menu ()
{
 cat << EOF
脚本路径:$0
----------------------------------------
|**********ansible菜单**********|
----------------------------------------
`echo -e "\033[47;30m 可以在任意选择界面按"Ctrl+c"键退出\033[0m"`
`echo -e "\033[47;30m 0)执行playbook.sh\033[0m"`
`echo -e "\033[47;30m 1)定义hosts及roles路径默认:ansible.cfg\033[0m"`
`echo -e "\033[47;30m 2)显示hosts文件和roles目录\033[0m"`
`echo -e "\033[47;30m 3)查看常用ansible命令\033[0m"`
`echo -e "\033[47;30m 4)ping模块\033[0m"`
`echo -e "\033[47;30m 5)执行roles\033[0m"`
`echo -e "\033[47;30m 6)查看roles\033[0m"`
`echo -e "\033[47;30m 7)手动命令\033[0m"`
`echo -e "\033[47;30m 8)编辑hosts文件\033[0m"`
`echo -e "\033[47;30m 9)返回主菜单\033[0m"`
`echo -e "\033[47;30m exit)退出\033[0m"`
EOF
read -p "请输入功能对应的数字：" num1
while [ $num1 != 'exit' ];do
case $num1 in
 0)
   $basepath/playbook.sh
   exit 0
   menu
   ;;
 1)
   clear
   read -p "输入hosts文件的绝对路径:" inventory
   sed -i "/^#inventory /cinventory      = $inventory" ansible.cfg
   sed -i "/^inventory /cinventory      = $inventory" ansible.cfg
   read -p "输入roles文件的绝对路径:" roles
   sed -i "/^#roles_path/croles_path    = $roles" ansible.cfg
   sed -i "/^roles_path/croles_path    = $roles" ansible.cfg
   menu
   ;;
 2)
   clear
   inventory=$(egrep "^inventory " $basepath/ansible.cfg|awk {'print $3'})
   inventory=$basepath/$inventory
   roles=$(egrep "^roles_path" $basepath/ansible.cfg|awk {'print $3'})
   roles=$basepath/$roles
   echo hosts:$inventory
   echo roles:$roles
   menu
   ;;
 3)
   clear

   menu
   ;;
 4)
   clear
   cat $inventory
   read -p "输入要Ping的主机:" host
   echo "ansible $host -m ping"
   ansible $host -m ping
   menu
   ;;
 5)
   clear
   cat $inventory
   read -p "输入主机:" host
   ls --color $roles
   read -p "输入role:" role
   echo "ansible-playbook $roles/$role/site.yml -e host=$host -e role=$role"
   ansible-playbook $roles/$role/site.yml -e host=$host -e role=$role
   menu
   ;;
 6)
   clear
   echo "ls $roles"
   ls --color=tty $roles

   menu
   ;;
 7)
   clear
   read -p "输入手动命令:" command
   echo "$command"
   $command
   menu
   ;;
 8)
   clear
   vi $inventory
   menu
   ;;
 9)
   clear
   bash $basepath/$scriptName
   exit 0
   ;;
 exit)
   exit 0
esac
done
}
menu
